package cn.lazyturtle.bugpush.service.impl;

import cn.lazyturtle.bugpush.bo.BugBo;
import cn.lazyturtle.bugpush.dao.user.UserDao;
import cn.lazyturtle.bugpush.service.PushBugService;
import cn.lazyturtle.bugpush.utils.DingTalkUtils;
import cn.lazyturtle.bugpush.utils.HttpUtils;
import cn.lazyturtle.bugpush.vo.bug.BugDescribeVo;
import cn.lazyturtle.bugpush.vo.bug.DynamicBugVo;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static cn.lazyturtle.bugpush.constant.CommonConstant.*;
import static cn.lazyturtle.bugpush.constant.RedisKeyEnum.LAST_DYNAMIC_BUG_ID_STRING;
import static cn.lazyturtle.bugpush.constant.RedisKeyEnum.USER_NAME_MAP_STRING;


/**
 * <p>
 * PushBugServiceImpl :
 * </p>
 *
 * @author cwh
 * @since 2021-09-01
 */
@Service
@Slf4j
public class PushBugServiceImpl implements PushBugService {
    private final RedisTemplate<String,String> redisTemplate;
    private final UserDao userDao;
    private final DingTalkUtils dingTalkUtils;
    @Value("${http.python.push-bug}")
    private String pushBugUrl;
    @Value("${http.python.push-users}")
    private String pushUsersUrl;
    @Value("${http.python.basic-bug-url}")
    private String basicBugUrl;
    @Value("${http.python.basic-image}")
    private String basicImage;

    @Autowired
    public PushBugServiceImpl(RedisTemplate<String, String> redisTemplate, UserDao userDao, DingTalkUtils dingTalkUtils) {
        this.redisTemplate = redisTemplate;
        this.userDao = userDao;
        this.dingTalkUtils = dingTalkUtils;
    }

    @Override
    public void getLastDynamicBug() {
        String response = HttpUtils.doPostByJson(pushBugUrl, null);
        log.info("抓取数据长度:{}",response.length());
        JSONObject jsonObject = JSONObject.parseObject(response);

        JSONArray jsonDynamicBugList = jsonObject.getJSONArray("dynamicBugVoList");
        if (Objects.isNull(jsonDynamicBugList)){
            log.info("没有新动态");
            return;
        }
        Map<String, String> userMap = userDao.selectUser();

        List<DynamicBugVo> dynamicBugVoList = jsonDynamicBugList.toJavaList(DynamicBugVo.class);
        List<BugDescribeVo> bugDescribeVoList = jsonObject.getJSONArray("bugDescribeVoList").toJavaList(BugDescribeVo.class);
        Map<String, BugDescribeVo> bugDescribeVoMap = bugDescribeVoList.stream().collect(Collectors.toMap(BugDescribeVo::getId, bugDescribeVo -> bugDescribeVo));
        // 从缓存取出上次扫描到的位置指针
        String oLastDynamicBugId = redisTemplate.opsForValue().get(LAST_DYNAMIC_BUG_ID_STRING);
        log.info("指针位置:{}",oLastDynamicBugId);
        int lastDynamicBugId = 0;
        if (Objects.nonNull(oLastDynamicBugId)){
            lastDynamicBugId = Integer.parseInt(oLastDynamicBugId);
        }
        // 获取动态,更新指针
        String userName = redisTemplate.opsForValue().get(USER_NAME_MAP_STRING);
        Map<?,?> userNameMap = Optional.ofNullable(JSONObject.parseObject(userName, Map.class)).orElse(new HashMap<String,String>());
        List<BugBo> bugBoList = new ArrayList<>();
        int finalLastDynamicBugId = lastDynamicBugId;
        AtomicInteger maxDynamicBugId = new AtomicInteger(lastDynamicBugId);
        dynamicBugVoList.forEach(dynamicBugVo -> {
            int dynamicBugVoId = Integer.parseInt(dynamicBugVo.getId());
            // 动态id大于指针位置，过滤关闭信息
            if (dynamicBugVoId > finalLastDynamicBugId && !CLOSED_BUG.equals(dynamicBugVo.getActionLabel())) {
                // 更新指针
                if (dynamicBugVoId > maxDynamicBugId.get()) {
                    maxDynamicBugId.set(dynamicBugVoId);
                }
                // 封装bo
                String actionLabel = dynamicBugVo.getActionLabel();
                // 指派了
                if (ASSIGN_BUG.equals(actionLabel) || ACTIVATION_BUG.equals(actionLabel) || CREATE_BUG.equals(actionLabel)){
                    String objectId = dynamicBugVo.getObjectID();
                    BugDescribeVo bugDescribeVo = bugDescribeVoMap.get(objectId);
                    // bug详情不为空
                    if (Objects.nonNull(bugDescribeVo)){
                        String assignedTo = bugDescribeVo.getAssignedTo();
                        String dingDingUserId = userMap.get(assignedTo);
                        String actor = dynamicBugVo.getActor();
                        Object actorName = userNameMap.get(actor);
                        if (Objects.nonNull(actorName)){
                            actor = actorName.toString();
                        }
                        if (StringUtils.hasText(dingDingUserId)){
                            BugBo bugBo = BugBo.builder()
                                .id(dynamicBugVo.getId())
                                .objectID(dynamicBugVo.getObjectID())
                                .objectName(dynamicBugVo.getObjectName())
                                .actionLabel(dynamicBugVo.getActionLabel())
                                .actor(actor)
                                .assignedTo(assignedTo)
                                .pushUserId(dingDingUserId)
                                .objectLink(getLink(dynamicBugVo.getObjectLink()))
                                .time(dynamicBugVo.getTime())
                                .build();
                            bugBoList.add(bugBo);
                        }
                    }
                }
            }
        });

        List<BugBo> bugBos = bugBoList.stream().sorted(Comparator.comparing(BugBo::getId)).collect(Collectors.toList());
        // 推送bug
        bugBos.forEach(bugBo -> {
            log.info("推送给:{},消息内容:{}",bugBo.getAssignedTo(),bugBo);
            String title = bugBo.getActor()+bugBo.getActionLabel()+"bug给你\t"+bugBo.getTime();
            dingTalkUtils.sendWorkNotify(dingTalkUtils.getToken(), bugBo.getPushUserId(),title,bugBo.getObjectName(), bugBo.getObjectLink(),basicImage);
        });

        redisTemplate.opsForValue().set(LAST_DYNAMIC_BUG_ID_STRING, String.valueOf(maxDynamicBugId));
    }

    @Override
    public void getNameMap() {
        String response = HttpUtils.doPostByJson(pushUsersUrl, null);
        Map<?,?> map = JSONObject.parseObject(response, Map.class);
        redisTemplate.opsForValue().set(USER_NAME_MAP_STRING, JSONObject.toJSONString(map));
    }

    private String getLink(String objectLink){
        if (!StringUtils.hasText(objectLink)){
            return null;
        }
        String replace = objectLink.replace(".json", ".html");
        return basicBugUrl + replace;
    }

}
